package top.jacktgq.itheima.netty.protocol_design.groupchat.message;

import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import lombok.ToString;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.service.UserService;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.service.UserServiceFactory;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.session.SessionFactory;

@Data
@ToString(callSuper = true)
public class LoginRequestMessage extends Message {
    private String username;
    private String password;

    public LoginRequestMessage() {
    }

    public LoginRequestMessage(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @Override
    public int getMessageType() {
        return LoginRequestMessage;
    }

    @Override
    public void handle(ChannelHandlerContext ctx) {
        // 处理用户登录的逻辑
        UserService userService = UserServiceFactory.getUserService();
        String reason = "用户名或密码错误，请重试！";
        boolean success = userService.login(username, password);
        if (success) {
            SessionFactory.getSession().bind(ctx.channel(), username);
            reason = "登录成功！";
        }
        ctx.writeAndFlush(new LoginResponseMessage(success, reason));
    }
}
